let storedElemIds = [];

const genState = () => {
  const state = { elems: {} };
  for (const elemId of storedElemIds) {
    const elem = document.getElementById(elemId);
    state.elems[elemId] = elem.outerHTML;
  }
  return state;
};

export const softReloadSetup = (elemIds) => {
  storedElemIds = elemIds;
  window.addEventListener("popstate", (event) => {
    if (event.state && event.state.elems) {
      console.log(event.state.elems);
      for (const elemId of storedElemIds) {
        document.getElementById(elemId).outerHTML = event.state.elems[elemId];
      }
    }
  });
  window.history.replaceState(genState(), "", window.location.href);
};

export const softReloadForm = (form, elemIds, options) => {
  options ||= {};
  form.addEventListener("submit", (event) => {
    event.preventDefault();
    const formData = new FormData(form);
    const url = new URL(window.location.href);
    const isGet = form.method.toLowerCase() === "get";
    url.search = isGet ? new URLSearchParams(formData) : "";
    for (const elemId of elemIds) {
      document.getElementById(elemId).classList.add("loading");
    }
    fetch(url, { method: form.method, body: isGet ? undefined : formData })
      .then((response) => response.text())
      .then((html) => {
        if (options.reset) {
          form.reset();
        }
        const doc = new DOMParser().parseFromString(html, "text/html");
        for (const elemId of elemIds) {
          const elem = document.getElementById(elemId);
          elem.outerHTML = doc.getElementById(elemId).outerHTML;
        }
        window.history.pushState(genState(), "", url);
      })
      .catch(() => {
        for (const elemId of elemIds) {
          document.getElementById(elemId).classList.remove("loading");
        }
        alert("Ztraceno připojení k internetu");
      });
  });
};
